

/**
 * @author hu-snail 1217437592@qq.com
 * @description 常用公共工具函数
 */
import axios from 'axios';
import { setting } from '@/config/setting';
const { title } = setting;

export const getPageTitle = (pageTitle) => {
  if (pageTitle) {
    return `${pageTitle}-${title}`;
  }
  return `${title}`;
};

// query序列化
export const p2q = (param) => {
  if (param == undefined) return '';
  let query = '';
  Object.keys(param).forEach((e, i) => {
    query += `${i === 0 ? '?' : '&'}${e}=${param[e]}`;
  });
  return query;
};

/*
 * format date
 * @param value
 * @param format type (eg...yyyy-MM-dd)
 * @return fomatted date string
 */
export const dateFormat = (value, fmt) => {
  if (!value) return '-';

  fmt = fmt || 'yyyy-MM-dd hh:mm:ss';

  const d = new Date(value);

  const o = {
    'M+': d.getMonth() + 1,
    'd+': d.getDate(),
    'h+': d.getHours(),
    'm+': d.getMinutes(),
    's+': d.getSeconds(),
    'q+': Math.floor((d.getMonth() + 3) / 3),
    S: d.getMilliseconds(),
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      );
    }
  }
  return fmt;
};

export class Storage {
  constructor() { }
  static getLoc(key) {
    return JSON.parse(localStorage.getItem(key));
  }
  static setLoc(obj) {
    localStorage.setItem(obj.key, JSON.stringify(obj.value));
  }
  static removeLoc(key) {
    localStorage.removeItem(key);
  }
  static getSession(key) {
    return JSON.parse(sessionStorage.getItem(key));
  }
  static setSession(obj) {
    sessionStorage.setItem(obj.key, JSON.stringify(obj.value));
  }
}
/**
 * 下载文件
 * @param {*} name 文件名
 * @param {*} blob 流
 */
export const downLoadFile = (name, blob) => {
  try {
    const a = document.createElement('a');
    a.download = name;
    const downloadUrl = (window.URL || window.webkitURL).createObjectURL(blob);
    a.href = downloadUrl;
    a.click();
    URL.revokeObjectURL(downloadUrl)
  } catch (e) {
    console.log(e)
  }

}

export const downLoadFileByUrl = (name, url) => {
  console.log(name, url)
 const a=document.createElement('a');
 a.href=url;
 a.download=name;
 a.style.display='none';
 document.body.appendChild(a);
 a.click();
 document.body.removeChild(a);
}

//获取门店类型，以及门店code
export const getStoreCodeAndType = (role) => {
  let parmas = {}
  console.log('role.roleKeyrole.roleKey', role.roleKey)
  // 经销商角色
  if (/dealer/.test(role.roleKey)) {
    parmas.codeType = 'D'
    parmas.storeCode = role.dealerCode
  } else if (/store/.test(role.roleKey)) {
    parmas.codeType = 'S'
    parmas.storeCode = role.dealerStoreCode
  }
  return parmas
}

// 水印
export const waterMark = () => {
  const repeatWatermark = document.querySelector('#repeat-watermark')
  if (repeatWatermark) {
    document.body.removeChild(repeatWatermark)
  }

  if (!Storage.getLoc('userInfo')) {
    return
  }
  const { userName } = Storage.getLoc('userInfo')

  // 绘制
  const canvasNode = document.createElement('canvas')
  canvasNode.id = 'watermark'
  canvasNode.width = '200'
  canvasNode.height = '200'
  // canvasNode.style = 'display: none;'
  // document.body.appendChild(canvasNode)
  // const canvas = document.querySelector('#watermark')
  const ctx = canvasNode.getContext('2d')
  ctx.font = '14px PorscheNextRegular SimHei sans-serif'
  ctx.fillStyle = 'rgba(100,100,100,.1)'
  ctx.rotate((-16 * Math.PI) / 180)
  ctx.fillText(`${userName}`, -10, 50)
  // ctx.rotate(45 * Math.PI / 180)
  const tplr = document.createElement('canvas')
  tplr.id = 'repeat-watermark'
  tplr.style = 'width:100vw;height:100vh;position:fixed;top:0;left:0;pointer-events:none;z-index:10;'
  document.body.appendChild(tplr)
  const crw = document.querySelector('#repeat-watermark')
  crw.width = document.body.offsetWidth
  crw.height = document.body.offsetHeight
  const ctxr = crw.getContext('2d')
  ctxr.clearRect(0, 0, crw.width, crw.height) //清除整个画布
  const pat = ctxr.createPattern(canvasNode, 'repeat') //在指定的方向上重复指定的元素
  ctxr.fillStyle = pat
  ctxr.fillRect(0, 0, crw.width, crw.height) /*  */
}

//获取字典的label
export const getDicLabel = (dic, val, defaultName) => {
  const obj = (dic || []).filter(item => item.value !== undefined).find(item => item.value === val) || { label: defaultName || '' }
  return obj.label
}
//获取字典的value
export const getDicValue = (dic, val, defaultValue) => {
  const obj = (dic || []).filter(item => item.value !== undefined).find(item => item.value === val) || { label: defaultValue || '' }
  return obj.value
}
//获取字典的Obj
export const getDicObj = (dic, val, defaultName) => {
  const obj = (dic || []).filter(item => item.value !== undefined).find(item => item.value === val) || {}
  return obj || {}
}
// 微信表情包匹配
export const emotion = [
  '[微笑]',
  '[撇嘴]',
  '[色]',
  '[发呆]',
  '[得意]',
  '[流泪]',
  '[害羞]',
  '[闭嘴]',
  '[睡]',
  '[大哭]',
  '[尴尬]',
  '[发怒]',
  '[调皮]',
  '[呲牙]',
  '[惊讶]',
  '[难过]',
  '[酷]',
  '[冷汗]',
  '[抓狂]',
  '[吐]',
  '[偷笑]',
  '[可爱]',
  '[白眼]',
  '[傲慢]',
  '[饥饿]',
  '[困]',
  '[惊恐]',
  '[流汗]',
  '[憨笑]',
  '[大兵]',
  '[奋斗]',
  '[咒骂]',
  '[疑问]',
  '[嘘]',
  '[晕]',
  '[折磨]',
  '[衰]',
  '[骷髅]',
  '[敲打]',
  '[再见]',
  '[擦汗]',
  '[抠鼻]',
  '[鼓掌]',
  '[糗大了]',
  '[坏笑]',
  '[左哼哼]',
  '[右哼哼]',
  '[哈欠]',
  '[鄙视]',
  '[委屈]',
  '[快哭了]',
  '[阴险]',
  '[亲亲]',
  '[吓]',
  '[可怜]',
  '[菜刀]',
  '[西瓜]',
  '[啤酒]',
  '[篮球]',
  '[乒乓]',
  '[咖啡]',
  '[饭]',
  '[猪头]',
  '[玫瑰]',
  '[凋谢]',
  '[示爱]',
  '[爱心]',
  '[心碎]',
  '[蛋糕]',
  '[闪电]',
  '[炸弹]',
  '[刀]',
  '[足球]',
  '[瓢虫]',
  '[便便]',
  '[月亮]',
  '[太阳]',
  '[礼物]',
  '[拥抱]',
  '[强]',
  '[弱]',
  '[握手]',
  '[胜利]',
  '[抱拳]',
  '[勾引]',
  '[拳头]',
  '[差劲]',
  '[爱你]',
  '[NO]',
  '[OK]',
  '[爱情]',
  '[飞吻]',
  '[跳跳]',
  '[发抖]',
  '[怄火]',
  '[转圈]',
  '[磕头]',
  '[回头]',
  '[跳绳]',
  '[挥手]',
  '[激动]',
  '[街舞]',
  '[献吻]',
  '[左太极]',
  '[右太极]',
]

// 时间差
export function diffDate(startDate, endDate) {
  if (!startDate || !endDate) {
    return
  }
  const start = new Date(startDate)
  const end = new Date(endDate)
  const diff = (end - start) / 1000
  console.log(diff)
  const days = parseInt(diff / 86400)
  const hours = parseInt(diff / 3600) - 24 * days
  const minutes = parseInt((diff % 3600) / 60)
  const seconds = parseInt(diff % 60)
  if (hours) {
    return hours + 'h' + minutes + 'm' + seconds + 's'
  }
  if (minutes) {
    return minutes + 'm' + seconds + 's'
  }
  return seconds + 's'
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
//获取字典对应label
export const getLabelByDic = (dic, val) => {
  const obj = (dic || []).find(item => item.value == val) || { label: '' }
  return obj.label
}
//获取字典对应对象
export const getObjByDic = (dic, val, defaultVal) => {
  const obj = (dic || []).find(item => item.value == val)
  return obj || {}
}

//获取字典对应value
export const getValueByDic = (dic, val) => {
  const obj = (dic || []).find(item => item.value == val) || { value: '' }
  return obj.value
}